#include "schedule.h"
#include "ui_schedule.h"
#include "pack.h"
#include <QMessageBox>
#include <QItemSelectionModel>
#include <QStringList>
#include <QFile>

schedule::schedule(QWidget *parent) :
    QDialog(parent),
    ui(new Ui::schedule),
    model(new myTablelist(this)),
    tcpSocket(nullptr) // 明确初始化
{
    ui->setupUi(this);

    // 设置模型
    ui->tableView->setModel(model);

    //初始化QDateTimeEdit
    ui->dateTimeEdit->setDisplayFormat("yyyy年MM月dd日 HH:mm");
    ui->dateTimeEdit->setCalendarPopup(true); //允许日历弹窗选择
    ui->dateTimeEdit->setDateTime(QDateTime::currentDateTime());  // 默认当前时间
    ui->dateTimeEdit->setMinimumDateTime(QDateTime(QDate(2000, 1, 1), QTime(0, 0))); // 最小日期时间
    ui->dateTimeEdit->setMaximumDateTime(QDateTime(QDate(2100, 12, 31), QTime(23, 59))); // 最大日期时间

    // 确保这些属性设置正确
    ui->tableView->setSelectionMode(QAbstractItemView::SingleSelection);
    ui->tableView->setSelectionBehavior(QAbstractItemView::SelectRows);
    ui->tableView->horizontalHeader()->setSectionResizeMode(QHeaderView::Interactive);
    ui->tableView->horizontalHeader()->setStretchLastSection(true);

    // 连接选中行变化信号
    connect(ui->tableView->selectionModel(), &QItemSelectionModel::currentRowChanged,
            this, &schedule::onCurrentRowChanged);

    // 设置列宽
    ui->tableView->setColumnWidth(0, 150);  // 日期列宽度
    ui->tableView->setColumnWidth(1, 300);  // 内容列宽度

    qDebug() << "TableView initialized";
    QFile file(":/interface.qss");
     if(file.open(QFile::OpenModeFlag::ReadOnly)){
         this->setStyleSheet(file.readAll());
     }
   // QObject::connect(tcpSocket,&QTcpSocket::connected,this,&schedule::loadDataAfterSocketReady);
}

schedule::~schedule() {
    delete ui;
}

void schedule::setSocket(QTcpSocket *socket) {
    tcpSocket = socket;
    // 移除重复的readyRead连接，由Widget统一分发
    if (tcpSocket) {
           QObject::connect(tcpSocket, &QTcpSocket::connected,
                            this, &schedule::loadDataAfterSocketReady);
       }
}

void schedule::onCurrentRowChanged(const QModelIndex &current, const QModelIndex &previous) {
    Q_UNUSED(previous);
    currentRow = current.row();
    if (currentRow >= 0) {
        ScheduleItem item = model->getItem(currentRow);

        QDateTime dateTime=QDateTime::fromString(item.date,"yyyy年MM月dd日 HH:mm");
        ui->dateTimeEdit->setDateTime(dateTime);
        ui->lineEdit_2->setText(item.event);
    }
}


void schedule::on_pushButton_save_clicked()
{
    QString date = ui->dateTimeEdit->dateTime().toString("yyyy年MM月dd日 HH:mm");   // 获取日期并去除首尾空格
    QString event = ui->lineEdit_2->text().trimmed(); // 获取


    // 构建协议包并发送
    Pack pack;
    pack.setType(TYPE_SCHEDULE_SAVE);
    pack << date << event;
    pack >> tcpSocket;
}

void schedule::on_pushButton_update_clicked()
{
    // 检查是否选中了有效行
    if (currentRow < 0) {
        QMessageBox::warning(this, "错误", "请先选择要更新的内容");
        return;
    }

    QString newDate = ui->dateTimeEdit->dateTime().toString();
    QString newEvent = ui->lineEdit_2->text().trimmed();
    QString oldDate = model->getItem(currentRow).date; // 获取原日期作为标识

    // 输入验证
    if (newDate.isEmpty() || newEvent.isEmpty()) {
        QMessageBox::warning(this, "输入错误", "日期和内容不能为空");
        return;
    }

    // 构建更新协议包
    Pack pack;
    pack.setType(TYPE_SCHEDULE_UPDATE);
    pack << oldDate << newDate << newEvent;
    pack >> tcpSocket;
}

void schedule::on_pushButton_find_clicked()
{
    QString date = ui->dateTimeEdit->dateTime().toString();

    // 构建查询协议包
    Pack pack;
    pack.setType(TYPE_SCHEDULE_QUERY);
    pack << date; // 发送查询日期
    pack >> tcpSocket;
}

void schedule::on_pushButton_del_clicked()
{
    // 检查是否选中了有效行
    if (currentRow < 0) {
        QMessageBox::warning(this, "错误", "请先选择要删除的上课情况");
        return;
    }

    QString date = model->getItem(currentRow).date;

    // 构建删除协议包
    Pack pack;
    pack.setType(TYPE_SCHEDULE_DELETE);
    pack << date;
    pack >> tcpSocket;
}

void schedule::on_pushButton_show_clicked()
{
    // 构建查询所有日程的协议包
    Pack pack;
    pack.setType(TYPE_SCHEDULE_QUERY_ALL);  // 明确使用查询所有类型
    pack << QString(""); // 显式转换为空QString避免重载歧义
    pack >> tcpSocket;
}

void schedule::loadDataAfterSocketReady()
{
    on_pushButton_show_clicked();
}

void schedule::handleScheduleResponse(const Pack& pack)
{
    qDebug() << "Received schedule packet, type:" << pack.getType();

    switch(pack.getType()) {
        case TYPE_SCHEDULE_SAVE:
        case TYPE_SCHEDULE_UPDATE:
        case TYPE_SCHEDULE_DELETE: {
            if(pack.getBack() == BACK_SUCCESS) {
                QString msg = (pack.getType() == TYPE_SCHEDULE_SAVE) ? "保存成功" :
                            (pack.getType() == TYPE_SCHEDULE_UPDATE) ? "更新成功" : "删除成功";
                QMessageBox::information(this, "成功", msg);
                on_pushButton_show_clicked(); // 刷新表格
            } else {
                QMessageBox::critical(this, "错误", "操作失败");
            }
            break;
        }
        // 在 schedule.cpp 的 handleScheduleResponse 中
        case TYPE_SCHEDULE_QUERY:
        case TYPE_SCHEDULE_QUERY_ALL: {
            model->clear();

            QStringList stringList = pack.readAll();  // 先获取QStringList
            std::vector<std::string> vec;            // 创建目标vector

            // 逐个转换并添加元素
            for (const QString& str : stringList) {
                vec.push_back(str.toStdString());    // 每个QString转成std::string
            }
            QStringList items;
            for (const auto& s : vec) {
                items << QString::fromStdString(s); // 逐个转换为 QString
            }
            qDebug() << "Received schedule items (converted):" << items; // 确认数据是否正确

            // 循环添加数据到模型
            for(int i = 0; i < items.size(); i += 2) {
                if(i + 1 >= items.size()) break;
                model->addSchedule({items[i], items[i+1]}); // 添加到模型
            }

            ui->tableView->resizeColumnsToContents();
            ui->tableView->viewport()->update();
            break;
        }
        default:  // 处理未明确列出的枚举值
            qDebug() << "Unhandled schedule packet type:" << pack.getType();
            break;
    }
}
